package com.zwb.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zwb.service.common.MailConstants;
import com.zwb.service.common.utils.ConversionUtil;
import com.zwb.service.pojo.Employee;
import com.zwb.service.pojo.MailLog;
import com.zwb.service.service.IEmployeeService;
import com.zwb.service.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 头发又黑又长
 * @Date 2022/9/11 0:13
 * @email zwb15083976291@163.com
 */
@Slf4j
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;


    @Autowired
    private IEmployeeService employeeService;

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件 发送定时任务
     * <p>
     * 每10 秒执行一次
     */

    @Scheduled(cron = "0/10 * * * * ? ")
    public void mailTask() {
        log.info("定时任务执行中----------------------------");
        List<MailLog> list = mailLogService.list(new LambdaQueryWrapper<MailLog>().eq(MailLog::getStatus, MailConstants.DELIVERING)
                .le(MailLog::getTryTime, new Date()));
        for (MailLog mailLog : list) {
            /*重试次数 超过3次 不在重试 */
            if (MailConstants.MAX_TRY_COUNT <= mailLog.getCount()) {
                mailLogService.update(new LambdaUpdateWrapper<MailLog>()
                        .eq(MailLog::getMsgId, mailLog.getMsgId())
                        .set(MailLog::getStatus, MailConstants.FAILURE)
                        .set(MailLog::getUpdateTime, new Date())
                );
            } else {
                mailLogService.update(new LambdaUpdateWrapper<MailLog>()
                        .eq(MailLog::getMsgId, mailLog.getMsgId())
                        .set(MailLog::getCount, mailLog.getCount() + 1)
                        .set(MailLog::getUpdateTime, new Date())
                        .set(MailLog::getTryTime, ConversionUtil.localDateTimeToDate(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)))
                );
                /* 发送邮件*/
                Employee employee = employeeService.getEmployeesByIn(Collections.singletonList(mailLog.getEid())).get(0);
                rabbitTemplate.convertAndSend(MailConstants.EXCHANGE_EMAIL,
                        MailConstants.EMAIL_ROUTING_KEY, employee, new CorrelationData(mailLog.getMsgId()));
            }

        }

    }
}
